package main

import (
	"crypto/tls"
	"fmt"
	"net"
	"net/mail"
	"net/smtp"
	"strings"
)

// dial using TLS/SSL
func dial(addr string) (*tls.Conn, error) {

	return tls.Dial("tcp", addr, nil)
}

// compose message according to "from, to, subject, body"
func composeMsg(from string, to string, subject string, body string) (message string) {
	// Setup headers
	headers := make(map[string]string)
	headers["From"] = from
	headers["To"] = to
	headers["Subject"] = subject
	// Setup message
	for k, v := range headers {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + body
	return
}

// send email over SSL
func Send(username, password, server, port, toAddr string, subject string, body string, ssl bool) (err error) {
	host, _, _ := net.SplitHostPort(server + ":" + port)

	auth := smtp.PlainAuth("", username, password, host)
	send_to := strings.Split(toAddr, ";")
	msg := []byte("To: " + toAddr + "\r\nFrom: " + username + "<" + username + ">\r\nSubject: " + subject + "\r\n" + "\r\n\r\n" + body)

	if !ssl {
		err := smtp.SendMail(host+":"+port, auth, username, send_to, msg)
		return err
	}

	conn, err := dial(server + ":" + port)
	if err != nil {
		return
	}
	smtpClient, err := smtp.NewClient(conn, host)
	if err != nil {
		return
	}
	err = smtpClient.Auth(auth)
	if err != nil {
		return
	}
	from := mail.Address{"", username}
	err = smtpClient.Mail(from.Address)
	if err != nil {
		return
	}

	for _, t := range send_to {
		to := mail.Address{"", t}
		err = smtpClient.Rcpt(to.Address)
		if err != nil {
			fmt.Println(err)
		}
		writer, err := smtpClient.Data()
		if err != nil {
			fmt.Println(err)
		}
		message := composeMsg(from.String(), to.String(), subject, body)
		_, err = writer.Write([]byte(message))
		if err != nil {
			fmt.Println(err)
		}
		err = writer.Close()
		if err != nil {
			fmt.Println(err)
		}
	}

	smtpClient.Quit()
	return nil
}

func main() {
	Send("hongbing.han@cfbond.cn", "password", "smtp.exmail.qq.com", "465", "95028555@qq.com;568883932@qq.com", "nihaossl", "nihaossl", true)
	//Send("xhochipe@163.com","password","smtp.163.com", "25", "95028555@qq.com;568883932@qq.com", "nihao", "nihao", false)

}
